from injector import inject
from dataclasses import dataclass

from internal.entitry.account_entitry import Account
from internal.exception import UnauthorizedException
from internal.service import JwtService,AccountService
from flask import Request
@inject
@dataclass
class Middleware:
    account_service:AccountService
    def request_loader(self, request: Request)->Account:
        account_token = self._validate_token(request)
        payload = self.account_service.get_info(account_token)
        print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
        print(payload)
        print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
        user = payload.get("data")
        account = Account(
            userId=user.get("userId"),
            is_authenticated = True,
            username=user.get("username"),
            userMobile=user.get("userMobile")
        )
        return account

    def _validate_token(self, request: Request) -> str:
        auth_header = request.headers.get("Authorization")
        if not auth_header:
            raise UnauthorizedException("该接口需要授权才能访问，请登录后尝试")
        if " " not in auth_header:
            raise UnauthorizedException("该接口需要授权才能访问，验证格式失败")
        auth_schema, account_token = auth_header.split(None, 1)
        if auth_schema.lower() != "bearer":
            raise UnauthorizedException("该接口需要授权才能访问，验证格式失败")
        return account_token
